package com.portal.innovation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.portal.innovation.common.Constant;
import com.portal.innovation.config.SysException;
import com.portal.innovation.utils.PageUtils;
import com.portal.innovation.dao.EnrollmentInfoDao;
import com.portal.innovation.pojo.EnrollmentInfo;
import com.portal.innovation.pojo.ExportEnrollmentInfo;
import com.portal.innovation.service.EnrollmentInfoService;
import com.portal.innovation.service.TagsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service("enrollmentInfoService")
public class EnrollmentInfoServiceImpl extends ServiceImpl<EnrollmentInfoDao, EnrollmentInfo> implements EnrollmentInfoService {

    @Autowired
    private TagsService tagsService;


    @Override
    public PageUtils queryPage(HashMap params) {
        Integer curPage = 1;
        Integer limit = 10;

        if(params.get(Constant.PAGE) != null){
            curPage = Integer.parseInt(params.get(Constant.PAGE).toString());
        }
        if(params.get(Constant.LIMIT) != null){
            limit = Integer.parseInt(params.get(Constant.LIMIT).toString());
        }
        //分页对象
        Page<EnrollmentInfo> page = new Page<>(curPage, limit);

        PageUtils pageUtils = new PageUtils(this.page(page, null));

        //查询标记
        for (Object o : pageUtils.getList()) {
            EnrollmentInfo info = (EnrollmentInfo) o;
            if(info.getTagId() != null){
                info.setTags(tagsService.getById(info.getTagId()));
            }
        }

        return pageUtils;
    }

    @Override
    public List<ExportEnrollmentInfo> getAll() {
        List<ExportEnrollmentInfo> result = new ArrayList<>();
        List<EnrollmentInfo> allData = list();
        for (EnrollmentInfo info : allData) {
            ExportEnrollmentInfo obj = new ExportEnrollmentInfo();
            BeanUtils.copyProperties(info, obj);
            if(info.getTagId() != -1){
                obj.setTag(tagsService.getById(info.getTagId()).getName());
            }
            result.add(obj);
        }
        return result;
    }

    @Override
    public void saveInfo(EnrollmentInfo enrollmentInfo) {
        enrollmentInfo.setRegistrationTime(new Date());
        QueryWrapper<EnrollmentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_no", enrollmentInfo.getStuNo());
        EnrollmentInfo isExits = getOne(wrapper);
        if (isExits != null){
            throw new SysException("重复报名");
        }
        save(enrollmentInfo);
    }
}